<?php

/**
 * Třída reprezentující playlist
 *
 * @author - Ladislav Kryštovský
 */
class Playlist implements PlaylistInterface, Iterator
{

    /**
     *
     * @var string
     */
    private $_name;



    private $_description;

    /**
     *
     * @var array[tracks]
     */
    private $_tracks;

    /**
     *
     * @param string $name
     * @param array $tracks
     */
    public function __construct($name, array $tracks)
    {
        $this->_name = $name;
        $this->_tracks = $tracks;
    }

    /**
     * Seznam grooveshark IDs pro playlist widget
     *
     * @return array
     */
    public function getSongIDs()
    {
        $songIDs = array();

        foreach ($this->_tracks as $track)
        {
            if (is_numeric($track))
            {
                $songIDs[] = $track;
            }
            elseif ($track instanceof Track)
            {
                $my_track = DbTrack::loadTrack($track);


                if (!empty($my_track))
                {
                    $songIDs[] = $my_track->getID();
                }
            }
        }

        return $songIDs;
    }

    /**
     *
     * @param User $user
     * @return integer
     */

    public function save(User $user)
    {
        $db = Zend_Db_Table::getDefaultAdapter();

        $set = array();
        $set['date_created'] = new Zend_Db_Expr('NOW()');
        $set['name'] = $this->_name;
        $set['user_id'] = $user->getID();

        $db->insert('playlist', $set);
        $playlist_id = $db->lastInsertId();

        $song_ids = $this->getSongIDs();
        $order = 0;

        $set = array();
        $set['playlist_id'] = $playlist_id;

        foreach ($song_ids as $song_id)
        {

            $set['track_id'] = $song_id;
            $set['custom_order'] = $order++;

            $db->insert('playlist_has_track', $set);
        }

        return $playlist_id;
    }

    /**
     *
     * @param integer $id
     * @return Playlist
     */

    public static function load($id)
    {
        $db = Zend_Db_Table::getDefaultAdapter();



        $select = $db->select()->from('playlist');
        $select->where('id = ?', $id);

        $info = $db->fetchRow($select);


        $select = $db->select();
        $select->from('playlist_has_track', array('track_id'));

        $select->where('playlist_id = ?', $id);
        $select->order('custom_order');

        $tracks = $db->fetchCol($select);

        return new self($info['name'], $tracks);
    }

    /**
     *
     * @return integer
     */
    public function count()
    {
        return count($this->_tracks);
    }

    /**
     *
     * @return array
     */
    public function getTracks()
    {
        return $this->_tracks;
    }

    /**
     *
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     *
     * @return Track
     */
    public function current()
    {
        return current($this->_tracks);
    }

    /**
     *
     * @return integer
     */
    public function key()
    {
        return key($this->_tracks);
    }

    /**
     *
     */
    public function next()
    {
        return next($this->_tracks);
    }

    /**
     *
     */
    public function rewind()
    {
        return reset($this->_tracks);
    }

    /**
     *
     * @return bool
     */
    public function valid()
    {
        return key($this->_tracks) !== null;
    }


    public function publish(User $user)
    {
        $fm = LastFM::getInstance();

        $playlistInfo = $fm->playlist_create(array(
            "title" => $this->getName(),
//            "description" => $this->_description,
            "api_sig" => true,
            "sk" => $user->getSessionKey()
                ));

        $playlist_id = (int)$playlistInfo->playlist->id;

        try
        {
        foreach ($this->getDbTracks() as $track)
        {
            $songInfo = $fm->playlist_addTrack(array(
                "playlistID" => $playlist_id,
                "track" => $track->getSong(),
                "artist" => $track->artist_name,
                "api_sig" => true,
                "sk" => $user->getSessionKey()));

        }
        }
        catch
        (Exception $e)
        {

            }

    }

    public function getDbTracks()
    {
        $tracksX = new DbTracks();

        $songIDs = $this->getSongIDs();


        $tracks = array();
        foreach ($songIDs as $songID)
        {

            $tracks[] = $tracksX->find($songID)->current();
        }

        return $tracks;

    }

    public static function lxoad($id)
    {
        $db = Zend_Db_Table::getDefaultAdapter();

        $playlist = new Playlist();

        $select = $db->select();
        $select->from('playlist_has_track', array('track_id'));
        $select->where('playlist_id = ?', $id);
        $select->order('custom_order');

        $songIDs = $db->fetchCol($select);

                    $tracks = new DbTracks();




                    $tracks = array();

        foreach ($songIDs as $songID)
        {

            $tracks[] = $tracks->find($songID)->current();
        }

        $select = $db->select()->from('playlist');
        $select->where('id = ?', $id);

        $info = $db->fetchRow($select);

        $name = $info->name;


        $playlist = new Playlist($name, $tracks);

        return $playlist;
    }

    public static function fetch($id)
    {
        $fm = LastFM::getInstance();

        $p = $fm->playlist_fetch(array("playlistURL" => "lastfm://playlist/$id"));

        $tracks = array();

        $playlist_name = (string)$p->playlist->title;
        
        foreach ($p->playlist->trackList->track as $track)
        {
            $title = (string)$track->title;
            $artist = (string)$track->creator;

            $title = str_replace(" - ", "", $title);
            $title = str_replace($artist, "", $title);

            $tracks[] = new Track($title, $artist);
        }

        return new Playlist($playlist_name, $tracks);
    }
}
